﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using 物业自助服务系统.Utils;
using System.Net;
using System.IO;
using System.Xml;
using System.Windows.Media.Animation;
using System.Timers;
using System.Collections;
using System.Threading;
using HtmlAgilityPack;
using 物业自助服务系统.Model;

namespace 物业自助服务系统.News
{
    /// <summary>
    /// NewsPage.xaml 的交互逻辑
    /// </summary>
    public partial class NewsPage : Page
    {
        ScrollViewer sv1 = null;
        ScrollViewer sv2 = null;
        ScrollViewer sv3 = null;
        ScrollViewer sv4 = null;
        ScrollViewer sv5 = null;
        ScrollViewer sv6 = null;
        StackPanel sp1 = null;
        StackPanel sp2 = null;
        StackPanel sp3 = null;
        StackPanel sp4 = null;
        StackPanel sp5 = null;
        StackPanel sp6 = null;
        Image image1 = null;
        Image image2 = null;
        Image image3 = null;
        Image image4 = null;
        Image image5 = null;
        Image image6 = null;
        TextBlock textBlock1 = null;
        TextBlock textBlock2 = null;
        TextBlock textBlock3 = null;
        TextBlock textBlock4 = null;
        TextBlock textBlock5 = null;
        TextBlock textBlock6 = null;

        int from = 0;//修改影响动画播放
        int to = 0;//修改影响动画播放
        int fontSize = 34;
        int ImageHeight = 260;//图片高度
        int ImageWidth=300;//单列宽度and图片宽度
        Thickness mar = new Thickness(16,0,16,0);//列间距
        public NewsPage()
        {
            InitializeComponent();
            GetNews("http://cq.gov.cn/rss/zfdt.xml");
            startScroll();
            TimerAnimation.Start(this,120,TimeSurplus,TimerImage);
        }
        /// <summary>
        /// 获取新闻列表
        /// </summary>
        /// <param name="url">地址</param>
        public void GetNews(string url)
        {
                string str = null;
                WebRequest httpRequest = WebRequest.Create(url);
                httpRequest.Method = "GET";
                try
                {
                    WebResponse webResponse = httpRequest.GetResponse();
                    using (Stream stream = webResponse.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            str = sr.ReadToEnd();
                        }
                    }
                    if (str != null)
                        HtmlConvert(str);
                    webResponse.Close();
                }
                catch (Exception error) {
                    LogOutput.Output(error.Message); }
        }
        List<string> Newstitle =new List<string>();
        List<string> Newslink = new List<string>();
        List<string> NewsPubDate = new List<string>();
        public void HtmlConvert(string Html)
        {
            try
            {
                Html = Html.Replace("<title>政府动态</title>", "");
                Html = Html.Replace("<link>http://www.cq.gov.cn/zwgk/zfxx</link>", "");
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(Html);
                XmlNode root = xmlDoc.SelectSingleNode("rss/channel");
                XmlNodeList nodeList = root.ChildNodes;
                for (int iq = 0; iq < nodeList.Count; iq++)
                {
                    XmlNode xmln = nodeList[iq];
                    if (xmln.Name == "item")
                    {
                        XmlNodeList list = xmln.ChildNodes;
                        for (int i = 0; i < list.Count; i++)
                        {
                            XmlNode x = list[i];
                            if ("link".Equals(x.Name))
                            { Newslink.Add(x.InnerText); }//新闻链接
                            else if ("title".Equals(x.Name))
                            { Newstitle.Add(x.InnerText); }//新闻标题
                            else if ("pubDate".Equals(x.Name))
                            { NewsPubDate.Add(x.InnerText); }//更新时间
                        }
                    }
                }
            }
            catch (Exception error)
            { MessageBox.Show(error.Message); }
        }
        private void startScroll()//开始滚动页面()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval =5000;//滚动间隔
            timer.Elapsed += new ElapsedEventHandler((sender, e) =>
            {
                Scroll();
            });
            timer.Start();
            Scroll();
        }
        public void Scroll()//由startScroll调用，包括计时之前调用
        {
            try
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (LoadingText.Visibility == Visibility.Visible)
                        LoadingText.Visibility = Visibility.Collapsed;
                    for (int i = 1; i < 4; i++)
                    {
                        if (Newstitle.Count != 0)
                        {
                            initPane1("/Img/轮播图片/" + i + ".jpg", "    " + Newstitle.ToArray<string>()[i], Newslink.ToArray<string>()[i], NewsPubDate.ToArray<string>()[i], i);
                        }
                    }
                    for (int i = 4; i < 8; i++)
                    {
                        if (Newstitle.Count != 0)
                        {
                            initPane2("/Img/轮播图片/" + i + ".jpg", "    " + Newstitle.ToArray<string>()[i], Newslink.ToArray<string>()[i], NewsPubDate.ToArray<string>()[i], i);
                        }
                    }
                    if (from == 0 && to == 0)//第一个页面左移，同时为第二页面左移做准备
                    {
                        NewsAnimation.StartAnimation(NewsPane1, 1280, 0);
                        NewsAnimation.StartAnimation(NewsPane, 0, -1280);
                        from = 0;
                        to = -1280;
                    }
                    else if (from == 0 && to == -1280)//第二个页面左移，同时为第一页面左移做准备
                    {
                        NewsAnimation.StartAnimation(NewsPane1, 0, -1280);
                        NewsAnimation.StartAnimation(NewsPane, 1280, 0);
                        from = 0;
                        to = 0;
                    }
                }));
            }
            catch (Exception error) { MessageBox.Show(error.Message); }
        }
        /// <summary>
        /// 初始化动画面板参数
        /// </summary>
        /// <param name="imageSource">图片路径</param>
        /// <param name="Newstitle">标题</param>
        /// <param name="Newslink">链接</param>
        /// <param name="NewsPubDate">更新时间</param>
        /// <param name="i">加载第i个</param>
        public void initPane1(string imageSource,string Newstitle,string Newslink,string NewsPubDate,int i)//初始化展示元素属性
        {
            initObject();
            switch (i)
            {
                case 1:
                    image1.Source = new BitmapImage(new Uri(imageSource,UriKind.Relative));//路径
                    textBlock1.Text =Newstitle;//显示的信息
                    sp1.Children.Add(image1);
                    sp1.Children.Add(textBlock1);
                    sp1.Tag = Newslink;
                    sp1.Uid = (1).ToString();//设置id，为标题做索引源
                    sv1.Content = sp1;
                    NewsPane.Children.Add(sv1);
                    break;
                case 2:
                    image2.Source = new BitmapImage(new Uri(imageSource, UriKind.Relative));//路径
                    textBlock2.Text = Newstitle;
                    sp2.Children.Add(image2);
                    sp2.Children.Add(textBlock2);
                    sp2.Tag = Newslink;
                    sp2.Uid = (2).ToString();
                    sv2.Content = sp2;
                    NewsPane.Children.Add(sv2);
                    break;
                case 3:
                    image3.Source = new BitmapImage(new Uri(imageSource, UriKind.Relative));//路径
                    textBlock3.Text = Newstitle;
                    sp3.Children.Add(image3);
                    sp3.Children.Add(textBlock3);
                    sp3.Tag = Newslink;
                    sp3.Uid = (3).ToString();
                    sv3.Content = sp3;
                    NewsPane.Children.Add(sv3);
                    break;
            }
        }
        /// <summary>
        /// 初始化动画面板参数
        /// </summary>
        /// <param name="imageSource">图片路径</param>
        /// <param name="Newstitle">标题</param>
        /// <param name="Newslink">链接</param>
        /// <param name="NewsPubDate">更新时间</param>
        /// <param name="i">加载第i个</param>
        public void initPane2(string imageSource, string Newstitle,string Newslink,string NewsPubDate, int i)//初始化展示元素属性
        {
            initObject();
            switch (i)
            {
                case 4:
                    image4.Source = new BitmapImage(new Uri(imageSource, UriKind.Relative));//路径
                    textBlock4.Text = Newstitle;//显示的信息
                    sp4.Children.Add(image4);
                    sp4.Children.Add(textBlock4);
                    sv4.Content = sp4;
                    sp4.Tag = Newslink;
                    sp4.Uid = (4).ToString();
                    NewsPane1.Children.Add(sv4);
                    break;
                case 5:
                    image5.Source = new BitmapImage(new Uri(imageSource, UriKind.Relative));//路径
                    textBlock5.Text = Newstitle;
                    sp5.Children.Add(image5);
                    sp5.Children.Add(textBlock5);
                    sp5.Tag = Newslink;
                    sp5.Uid = (5).ToString();
                    sv5.Content = sp5;
                    NewsPane1.Children.Add(sv5);
                    break;
                case 6:
                    image6.Source = new BitmapImage(new Uri(imageSource, UriKind.Relative));//路径
                    textBlock6.Text = Newstitle;
                    sp6.Children.Add(image6);
                    sp6.Children.Add(textBlock6);
                    sp6.Tag = Newslink;
                    sp6.Uid = (6).ToString();
                    sv6.Content = sp6;
                    NewsPane1.Children.Add(sv6);
                    break;
            }
        }
        private void initObject()//初始化pane元素对象
        {
            sv1 = new ScrollViewer();
            sv2 = new ScrollViewer();
            sv3 = new ScrollViewer();
            sv4 = new ScrollViewer();
            sv5 = new ScrollViewer();
            sv6 = new ScrollViewer();
            sp1 = new StackPanel();
            sp2 = new StackPanel();
            sp3 = new StackPanel();
            sp4 = new StackPanel();
            sp5 = new StackPanel();
            sp6 = new StackPanel();
            sp1.MouseUp += new MouseButtonEventHandler(sp1_MouseUp);
            sp2.MouseUp += new MouseButtonEventHandler(sp1_MouseUp);
            sp3.MouseUp += new MouseButtonEventHandler(sp1_MouseUp);
            sp4.MouseUp += new MouseButtonEventHandler(sp1_MouseUp);
            sp5.MouseUp += new MouseButtonEventHandler(sp1_MouseUp);
            sp6.MouseUp += new MouseButtonEventHandler(sp1_MouseUp);
            image1 = new Image();
            image2 = new Image();
            image3 = new Image();
            image4 = new Image();
            image5 = new Image();
            image6 = new Image();
            textBlock1 = new TextBlock();
            textBlock2 = new TextBlock();
            textBlock3 = new TextBlock();
            textBlock4 = new TextBlock();
            textBlock5 = new TextBlock();
            textBlock6 = new TextBlock();

            sv1.Background = new SolidColorBrush(Colors.Transparent);
            sv2.Background = new SolidColorBrush(Colors.Transparent);
            sv3.Background = new SolidColorBrush(Colors.Transparent);
            sv1.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            sv2.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            sv3.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            textBlock1.TextWrapping = TextWrapping.Wrap;
            textBlock2.TextWrapping = TextWrapping.Wrap;
            textBlock3.TextWrapping = TextWrapping.Wrap;
            textBlock1.FontSize = fontSize;
            textBlock2.FontSize = fontSize;
            textBlock3.FontSize = fontSize;
            sv1.Width = ImageWidth;
            sv2.Width = ImageWidth;
            sv3.Width = ImageWidth;
            image1.Width = ImageWidth;
            image2.Width = ImageWidth;
            image3.Width = ImageWidth;
            image1.Height = ImageHeight;
            image2.Height = ImageHeight;
            image3.Height = ImageHeight;
            sv1.Margin = mar;
            sv2.Margin = mar;
            sv3.Margin = mar;

            sv4.Background = new SolidColorBrush(Colors.Transparent);
            sv5.Background = new SolidColorBrush(Colors.Transparent);
            sv6.Background = new SolidColorBrush(Colors.Transparent);
            sv4.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            sv5.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            sv6.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            textBlock4.TextWrapping = TextWrapping.Wrap;
            textBlock5.TextWrapping = TextWrapping.Wrap;
            textBlock6.TextWrapping = TextWrapping.Wrap;
            textBlock4.FontSize = fontSize;
            textBlock5.FontSize = fontSize;
            textBlock6.FontSize = fontSize;
            sv4.Width = ImageWidth;
            sv5.Width = ImageWidth;
            sv6.Width = ImageWidth;
            image4.Width = ImageWidth;
            image5.Width = ImageWidth;
            image6.Width = ImageWidth;
            image4.Height = ImageHeight;
            image5.Height = ImageHeight;
            image6.Height = ImageHeight;
            sv4.Margin = mar;
            sv5.Margin = mar;
            sv6.Margin = mar;
        }
        private int GetRandomNumber(int max)//随机
        {
            Random rand = new Random();
            return rand.Next(max);
        }
        private string ConvertNewsContent(string text)
        {
            string content = null;
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(text);
            HtmlNode Node = doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[2]/div[2]/div[2]");
            string name= Node.Name;
            string boday = Node.InnerHtml;
            content = boday;

            //int index = text.IndexOf("<div class=" + "\"in_topicfont center\"" + ">");
            //content = text.Remove(0, index);
            //int Lastindex = content.LastIndexOf("</div>");
            //content = content.Remove(Lastindex, Lastindex);
            return content;
        }
        void sp1_MouseUp(object sender, MouseButtonEventArgs e)
        {
            string content = null;
            StackPanel pane = sender as StackPanel;
            string url = pane.Tag.ToString();
            int Titleindex =Convert.ToInt16(pane.Uid);
            ThreadStart ts = new ThreadStart(() =>
            {
                WebRequest request = WebRequest.Create(url);
                request.Method = "GET";
                WebResponse response = request.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        content = sr.ReadToEnd();
                    }
                }
                if (content != null)
                {
                    NewsContent.content.Add(Newstitle[Titleindex]);//标题,点击的stackpane的名字-1(1开始)
                    NewsContent.content.Add(ConvertNewsContent(content));
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        //NewsContent.image = image1;
                        if (this.NavigationService!=null)
                        this.NavigationService.Navigate(new Uri(@"\News\NewsDetails.xaml", UriKind.Relative));
                    }));
                }
            });
            Thread thread = new Thread(ts);
            thread.Start();
        }
        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri(@"\Home\HomePage.xaml", UriKind.Relative));
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.NavigationService.CanGoBack)
                this.NavigationService.GoBack();
        }
    }
}
